package com.ly.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 小球通过键盘上下左右的移动，讲解java的事件控制*/
public class BallMove extends JFrame {
    MyPanel mp=null;
    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }
    //构造器
    public BallMove(){
        mp=new MyPanel();
        this.add(mp);
        this.setSize(400,300);
        //加入监听
        this.addKeyListener(mp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}
//面板 可以画小球
//KeyListener是个监听器，可以监听键盘事件
class MyPanel extends JPanel implements KeyListener {
    int x=10;
    int y=20;
    @Override
    public void paint(Graphics g) {
        super.paint(g);

        g.fillOval(x,y,20,20);
    }
    //有字符输出时，该方法就会触发
    @Override
    public void keyTyped(KeyEvent e) {

    }
    //当某个键按下，该方法就会触发
    @Override
    public void keyPressed(KeyEvent e) {
//        System.out.println((char) e.getKeyCode()+"按下了...");
        //根据用户按不同键，处理小球的移动
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            y+=5;
            //让面板重绘
            this.repaint();
            System.out.println("down");
        }else if(e.getKeyCode()==KeyEvent.VK_UP){
            y-=5;
            //让面板重绘
            this.repaint();
            System.out.println("up");
        }else if(e.getKeyCode()==KeyEvent.VK_LEFT){
            x-=5;
            //让面板重绘
            this.repaint();
            System.out.println("left");
        }else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            x+=5;
            //让面板重绘
            this.repaint();
            System.out.println("right");
        }
    }
    //当某个键释放，该方法就会触发
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
